package docker_agent

import (
	devstar_devcontainer_models "code.gitea.io/gitea/models/devstar_devcontainer"
	"code.gitea.io/gitea/modules/log"
	"context"
	"github.com/docker/docker/api/types"
)

func AssignDevcontainerDeletionDockerOperator(ctx *context.Context, devcontainersList *[]devstar_devcontainer_models.DevstarDevcontainer) error {
	log.Info("Docker delete container")
	// 1. 创建docker client
	cli, err := CreateDockerClient(ctx)
	defer cli.Close()
	if err != nil {
		return err
	}
	// 获取容器 ID
	containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{All: true})
	if err != nil {
		log.Info("获取容器列表失败: %v", err)
	}

	var containerIDList []string
	for _, c := range containers {
		log.Info("containersIDList: %v", c.ID)
		for _, name := range c.Names {
			log.Info("containerNameList: %v", name)
			for _, devcontainer := range *devcontainersList {
				log.Info("devcontainerName: %v", devcontainer.Name)
				if name == "/"+devcontainer.Name {
					containerIDList = append(containerIDList, c.ID)
				}
			}
		}
	}
	// 删除容器
	options := types.ContainerRemoveOptions{
		Force:         true,  // 强制删除正在运行的容器
		RemoveVolumes: true,  // 删除数据卷
		RemoveLinks:   false, // 删除链接（已弃用）
	}
	for _, id := range containerIDList {
		if err := cli.ContainerRemove(context.Background(), id, options); err != nil {
			log.Info("删除%s容器失败: %v", id, err)
		}
		log.Info("容器 %s 已成功删除\n", id)
	}
	return nil
}
